package com.yycx.module.bus.provider.handler.haiying.tasktodo.backorder;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.yycx.bpm.provider.common.handler.ProcessStartHandler;
import com.yycx.bpm.provider.model.ProcessInstanceRequest;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.utils.ApiAssert;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.client.entity.hy.BusPaymentOrder;
import com.yycx.module.bus.client.entity.hy.HyOrder;
import com.yycx.module.bus.client.enums.SendTypeEnum;
import com.yycx.module.bus.provider.service.BusPaymentService;
import com.yycx.module.bus.provider.service.hy.BusPaymentOrderService;
import com.yycx.module.bus.provider.service.hy.HyOrderService;
import com.yycx.msg.provider.websocket.WebSocketServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 海鹰退货通知单订单审核流程启动处理器（退货不更新在单数）
 *
 * @author zyf
 */
@Component
@DSTransactional
@Slf4j
public class HyBackOrderStartProcessHandler implements ProcessStartHandler {

    @Autowired
    private HyOrderService orderService;
    @Resource
    private WebSocketServerEndpoint socketServerEndpoint;
    @Autowired
    private BusPaymentOrderService paymentOrderService;
    @Autowired
    private BusPaymentService paymentService;

    /**
     * 初始化流程参数
     *
     * @param processInstanceRequest
     * @return
     */
    @Override
    public String init(ProcessInstanceRequest processInstanceRequest) {
        processInstanceRequest.setProcessKey("process_back_order_flp");
        processInstanceRequest.setTenantId("flp");
        return processInstanceRequest.getBusinessKey();
    }

    /**
     * 设置全局流程变量
     *
     * @param processInstanceRequest
     * @param definition
     * @return
     */
    @Override
    public Map<String, Object> initVariables(ProcessInstanceRequest processInstanceRequest, ProcessDefinition definition) {
        Map<String, Object> map = new HashMap<>(5);
        String businessKey = processInstanceRequest.getBusinessKey();
        HyOrder order = orderService.getById(businessKey);
        if (!order.getOrderState().equals(0)) {
            ApiAssert.failure("请勿重复提交");
        }
        Integer sendType = order.getSendType();
        ApiAssert.isNotEmpty("发货方式不能为空", sendType);
        map.put("orderNo", order.getOrderNo());
        map.put("companyId", order.getCompanyId());
        map.put("deptId", order.getDeptId());
        return map;
    }

    /**
     * 启动完成业务处理
     *
     * @param processInstanceRequest 请求参数
     * @param definition             流程定义
     * @param processInstance        流程实例
     * @param tasks                  任务列表
     * @param variables              流程变量
     */
    @Override
    @DSTransactional
    public Boolean afterComplete(ProcessInstanceRequest processInstanceRequest, ProcessDefinition definition, ProcessInstance processInstance, List<Task> tasks, Map<String, Object> variables) {
        String businessKey = processInstanceRequest.getBusinessKey();
        HyOrder busOrder = orderService.getById(businessKey);
        //List<Long> userIds = roleUserMapper.selectUserIdByRoleCode("ROLE_NQBZ", Long.parseLong(companyId.toString()));
        //socketServerEndpoint.sendMessage(2L, "订单审核", "您有新的订单待审核,单号:" + orderNo, userIds, 2);
        orderService.updateOrderState(Long.parseLong(businessKey), processInstance.getProcessInstanceId(), CommonConstants.ENABLED, CommonConstants.INT_0, 0);
        saveBusPaymentOrder(busOrder);
        return true;
    }

    /**
     * 保存认款退款记录
     *
     * @param order
     */
    private void saveBusPaymentOrder(HyOrder order) {
        //提取的发货单ID
        String parentId = order.getParentId();
        //发货方式
        Integer sendType = order.getSendType();
        List<BusPaymentOrder> paymentOrderList = paymentOrderService.selectByOrderId(parentId);
        //退货金额
        BigDecimal totalAmount = FlymeUtils.getBigDecimal(order.getTotalSaleAmount(), "0");
        if (SendTypeEnum.ZBJ.getCode().equals(sendType)) {
            //资保金金额
            totalAmount = FlymeUtils.getBigDecimal(order.getTotalBondAmount(), "0");
        }
        if (FlymeUtils.isNotEmpty(paymentOrderList)) {
            for (BusPaymentOrder paymentOrder : paymentOrderList) {
                BigDecimal useAmount = paymentOrder.getUseAmount();
                Long paymentId = paymentOrder.getPaymentId();
                //认款记录
                BusPayment busPayment = paymentService.getById(paymentId);
                ApiAssert.isNotEmpty("认款记录不存在", busPayment);
                totalAmount = totalAmount.add(useAmount);
                BusPaymentOrder backPaymentOrder = new BusPaymentOrder();
                backPaymentOrder.setOrderId(order.getOrderId());
                backPaymentOrder.setPaymentId(paymentId);
                backPaymentOrder.setCompanyId(order.getCompanyId());
                backPaymentOrder.setSendType(order.getSendType());
                backPaymentOrder.setAmountType(paymentOrder.getAmountType());
                backPaymentOrder.setTakeAmount(paymentOrder.getTakeAmount());
                backPaymentOrder.setCustomId(String.valueOf(order.getCustomId()));
                backPaymentOrder.setBankName(paymentOrder.getBankName());
                backPaymentOrder.setBankId(paymentOrder.getBankId());
                backPaymentOrder.setBankStatementId(paymentOrder.getBankStatementId());
                backPaymentOrder.setTakeDate(paymentOrder.getTakeDate());
                if (FlymeUtils.lezero(totalAmount)) {
                    BigDecimal amount = useAmount.multiply(new BigDecimal("-1"));
                    backPaymentOrder.setUseAmount(amount);
                    BigDecimal surplusAmount = FlymeUtils.getBigDecimal(busPayment.getSurplusAmount(), "0");
                    busPayment.setSurplusAmount(surplusAmount.subtract(amount));
                }
                if (FlymeUtils.gtzero(totalAmount)) {
                    BigDecimal amount = totalAmount.subtract(useAmount);
                    backPaymentOrder.setUseAmount(amount);
                    BigDecimal surplusAmount = FlymeUtils.getBigDecimal(busPayment.getSurplusAmount(), "0");
                    busPayment.setSurplusAmount(surplusAmount.subtract(amount));
                }
                //更新认款剩余金额
                paymentService.updateById(busPayment);
                paymentOrderService.save(backPaymentOrder);
                if (FlymeUtils.gtzero(totalAmount)) {
                    break;
                }
            }
        }

    }
}
